#include<iostream>
#include<vector>
#include<algorithm>
#include<queue>
#include<unordered_set>
using namespace std;

int dx[] = { 0,0,1,-1 };
int dy[] = { 1,-1,0,0 };

//位置{i,j}->位置{endi,endj}需要的步数
int bfs(vector<vector<char>>& arr, int i, int j, int endi, int endj) {
    int n = arr.size();
    int m = arr[0].size();
    unordered_set<int> vis;  // 使用 unordered_set 存储已访问位置
    queue < pair<int, int>>q;
    int len = 0;
    q.push({ i,j });
    vis.insert(i * m + j);  // 将二维位置映射为一维存储

    while (q.size()) {
        int sz = q.size();
        len++;
        while (sz--) {
            int a = q.front().first;
            int b = q.front().second;
            q.pop();
            for (int k = 0; k < 4; k++) {
                int x = a + dx[k];
                int y = b + dy[k];
                int index = x * m + y;//处理压缩下标
                if (x >= 0 && x < n && y >= 0 && y < m && vis.count(index) == 0 && arr[x][y] != '#') {
                    if (arr[endi][endj] == 'K' && arr[x][y] == 'E')continue;//如果我要到钥匙哪里,中间遇到门是过不去的
                    else if (arr[endi][endj] == 'E' && arr[x][y] == 'K')continue; //起始位置就是钥匙,只拿一把钥匙

                    if (x == endi && y == endj) {
                        return len;
                    }
                    q.push({ x,y });
                    vis.insert(index);
                }
            }
        }
    }
    return 0;
}


void solve() {
    int n, m; cin >> n >> m;
    vector<vector<char>>arr(n, vector<char>(m));
    int srci = 0; int srcj = 0;//人的起始坐标
    vector<pair<int, int>>key;//钥匙的坐标集合      
    int endi = 0; int endj = 0;//出口的坐标位置
    for (int i = 0; i < n; i++) {
        for (int j = 0; j < m; j++) {
            cin >> arr[i][j];
            if (arr[i][j] == 'P') {
                srci = i;
                srcj = j;
            }
            else if (arr[i][j] == 'K') {
                key.push_back({ i,j }); //添加钥匙集合
            }
            else if (arr[i][j] == 'E') {
                endi = i; endj = j;
            }
        }
    }
    int ret = 0x3f3f3f3f;
    //ret = bfs(arr, srci, srcj, keyi, keyj);
    //if (ret) {
    //    arr[keyi][keyj] = '.';  // 拿到钥匙后将钥匙位置标记为可通行
    //    ret += bfs(arr, keyi, keyj, endi, endj);
    //}
    //人到门==人到钥匙+钥匙到门

    //遍历钥匙集合
    for (int i = 0; i < key.size(); i++)
    {
        //获取钥匙的坐标
        int keyi = key[i].first;
        int keyj = key[i].second;
        int person_to_key = 0; int key_to_exit = 0;
         person_to_key = bfs(arr, srci, srcj, keyi, keyj); //人到钥匙的距离
        if(person_to_key)//拿到钥匙才能到门,否则结果为0
         key_to_exit = bfs(arr, keyi, keyj, endi, endj); //钥匙到们的距离
        //cout << person_to_key << "->" << key_to_exit << endl;    
        ret = min(ret, person_to_key + key_to_exit);    
     }  
    if (ret) cout << ret << endl;
    else
        cout << "No solution" << endl;
}


int main() {
    int t = 0; cin >> t;
    while (t--) {
        solve();
    }
    return 0;
}
